import { useCallback } from 'react';

export const useGamePersistence = (
  petState,
  setPetState,
  gameInfo,
  setGameInfo,
  setGameStarted,
  availablePets,
  setAvailablePets,
  setNotification
) => {
  const saveGame = useCallback(() => {
    try {
      // 直接保存当前状态
      const gameData = {
        petState,
        gameInfo,
        availablePets,
        lastSaved: new Date().toISOString()
      };
      
      localStorage.setItem('gameData', JSON.stringify(gameData));
      
      setNotification({
        message: '游戏已保存！',
        isVisible: true
      });
    } catch (error) {
      setNotification({
        message: '保存失败，请稍后重试！',
        isVisible: true
      });
    }
  }, [petState, gameInfo, availablePets, setNotification]);

  const loadGame = useCallback(() => {
    try {
      const savedData = localStorage.getItem('gameData');
      if (!savedData) {
        setNotification({
          message: '没有找到存档！',
          isVisible: true
        });
        return false;
      }

      const gameData = JSON.parse(savedData);
      
      // 检查数据完整性
      if (!gameData.petState || !gameData.gameInfo) {
        setNotification({
          message: '存档数据不完整！',
          isVisible: true
        });
        return false;
      }

      setPetState(gameData.petState);
      setGameInfo(gameData.gameInfo);
      setAvailablePets(gameData.availablePets || []);
      setGameStarted(true);
      
      setNotification({
        message: '游戏存档已加载！',
        isVisible: true
      });
      return true;
    } catch (error) {
      console.error('加载存档失败:', error);
      setNotification({
        message: '加载存档失败，请检查存档数据！',
        isVisible: true
      });
      return false;
    }
  }, [setPetState, setGameInfo, setAvailablePets, setGameStarted, setNotification]);

  return { saveGame, loadGame };
};